<template>
  <el-dialog
    title="添加广告"
    :visible.sync="visible"
    class="goods-dialog"
    :modal="false"
    :close-on-click-modal="false"
    :before-close="handleCloseDialog"
    width="1300px"
  >
    <div class="app-container">
      <el-card class="filter-container" shadow="never">
        <div>
          <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="mini"
          >
            查询搜索
          </el-button>
          <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="mini"
          >
            重置
          </el-button>
        </div>
        <div>
          <el-form
            :inline="true"
            :model="listQuery"
            size="mini"
            label-width="100px"
          >
            <el-form-item label="广告名称：">
              <el-input
                v-model="listQuery.goodsName"
                class="input-width"
                placeholder="请输入广告名称"
                clearable
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="广告分类：">
            <el-select
              v-model="listQuery.classifyId"
              placeholder="请选择广告分类"
            >
              <el-option
                v-for="item in classifyOptions"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          </el-form>
        </div>
      </el-card>
      <!-- <el-card class="operate-container" shadow="never">
        <i class="el-icon-tickets"></i>
        <span>广告列表</span>
        <el-button
          size="mini"
          type="success"
          class="btn-add"
          @click="handleAdd"
          style="margin-left: 20px"
          >添加广告</el-button
        >
      </el-card> -->
      <div class="table-container goods-list-container">
        <el-table
          ref="adminTable"
          :data="list"
          size="mini"
          style="width: 100%;"
          v-loading="listLoading"
          row-key="id"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="广告ID" width="160" align="center">
            <template slot-scope="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column label="广告图片" width="120" align="center">
            <template slot-scope="scope">
              <div v-viewer class="img-box">
                <img
                  :src="
                    scope.row.goodsPic
                      ? `${user.filePreviewUrl}/${scope.row.goodsPic}`
                      : ''
                  "
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="广告名称" align="center">
            <template slot-scope="scope">{{ scope.row.goodsName }}</template>
          </el-table-column>
          <el-table-column label="最低投入" width="160" align="center">
            <template slot-scope="scope">{{
              formatAmount(scope.row.minPrice)
            }}</template>
          </el-table-column>
          <el-table-column label="最高投入" width="160" align="center">
            <template slot-scope="scope">{{
              formatAmount(scope.row.maxPrice)
            }}</template>
          </el-table-column>
          <el-table-column label="库存" width="120" align="center">
            <template slot-scope="scope">{{ scope.row.goodsStock }}</template>
          </el-table-column>
          <el-table-column label="添加时间" width="180" align="center">
            <template slot-scope="scope">{{
              scope.row.createTime | formatDateTime
            }}</template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdata(scope.row)"
                >编辑</el-button
              >
              <el-button size="mini" type="text" @click="handleStock(scope.row)"
                >修改库存</el-button
              >
              <el-button
                size="mini"
                type="text"
                class="success"
                v-if="scope.row.state === 0"
                @click="handleChangeStatus(scope.row, 1)"
                >上架</el-button
              >
              <el-button
                size="mini"
                type="text"
                class="danger"
                v-else
                @click="handleChangeStatus(scope.row, 0)"
                >下架</el-button
              >
              <el-button
                size="mini"
                class="danger"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 新增/编辑  -->
      <edit-goods-dialog
        v-if="editVisible"
        :row="row"
        @handle-confirm="handleConfirm"
        @handle-cancel="editVisible = false"
      />

      <!-- 修改库存  -->
      <edit-stock-dialog
        v-if="stockVisible"
        :row="row"
        @handle-confirm="handleConfirm"
        @handle-cancel="stockVisible = false"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="handleConfirmDialog"
        size="mini"
        :loading="loading"
        >确 定</el-button
      >
      <el-button @click="handleCloseDialog" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  getGoodsList,
  upGoodsInfo,
  downGoodsInfo,
  deleteGoodsInfo
} from "@/api/goods/index";
import { formatDate } from "@/utils/date";
import { formatAmount, getStorage } from "@/utils/index";
import EditGoodsDialog from "./dialogs/edit-goods-dialog.vue";
import EditStockDialog from "./dialogs/edit-stock-dialog.vue";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  goodsName: null
};
export default {
  components: {
    EditGoodsDialog,
    EditStockDialog
  },
  props: {
    goodsList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      row: {},
      user: getStorage("user") || {},
      listLoading: false,
      editVisible: false,
      stockVisible: false,
      loading: false,
      visible: true,
      classifyOptions: [],
      multipleSelection: [],
      ids: []
    };
  },
  created() {
    this.ids = this.goodsList.map(item => {
      return item.id;
    });
    console.log("this.ids", this.ids);
    this.getList();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    formatAmount,
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleConfirm() {
      this.getList();
      this.editVisible = false;
      this.stockVisible = false;
    },

    // 添加
    handleAdd() {
      this.row = {};
      this.editVisible = true;
    },
    // 编辑
    handleUpdata(row) {
      this.row = row;
      this.editVisible = true;
    },
    //修改库存
    handleStock(row) {
      this.row = row;
      this.stockVisible = true;
    },
    //更改状态
    handleChangeStatus(row, status) {
      this.$confirm(`是否要${status === 1 ? "上架" : "下架"}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        if (status === 1) {
          await upGoodsInfo({ id: row.id });
        } else {
          await downGoodsInfo({ id: row.id });
        }
        this.$message({
          type: "success",
          message: `${status === 1 ? "上架" : "下架"}成功!`
        });
        this.getList();
      });
    },

    // 根据ID数组设置选中状态
    selectByIds() {
      this.$nextTick(() => {
        // 清空现有选中
        this.$refs.adminTable.clearSelection();
        // 遍历数据，设置选中
        this.list.forEach(row => {
          console.log("this.ids.includes(row.id)", this.ids.includes(row.id));
          if (this.ids.includes(row.id)) {
            console.log(this.$refs.adminTable);
            this.$refs.adminTable.toggleRowSelection(row, true);
          }
        });
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleConfirmDialog() {
      this.$emit("handle-confirm", this.multipleSelection);
    },
    handleCloseDialog() {
      this.$emit("handle-cancel");
    },

    //删除
    handleDelete(row) {
      this.$confirm("是否要删除广告?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteGoodsInfo({ id: row.id }).then(response => {
          this.$message({
            type: "success",
            message: "删除广告成功!"
          });
          this.getList();
        });
      });
    },

    getList() {
      this.listLoading = true;
      getGoodsList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
        this.selectByIds();
      });
    }
  }
};
</script>
<style lang="scss">
.success {
  color: #67c23a !important;
}
.danger {
  color: #f56c6c !important;
}

.goods-list-container {
  height: calc(100vh - 502px);
  .el-table__body-wrapper {
    height: calc(100vh - 545px);
    overflow: auto;
  }
}
.goods-dialog {
  .el-dialog__body {
    height: 60vh !important;
  }
}
</style>
